package com.lcifn.springmvc.controller;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

// @ControllerAdvice支持@ExceptionHandler，@InitBinder，@ModelAttribute
@ControllerAdvice
public class AdviceController {

	// @InitBinder 用于初始化 WebDataBinder 的方法
	// 也可使用WebBindingInitializer
	@InitBinder
	public void initBinder(WebDataBinder binder){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		sdf.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, false));
	}
	
	//@ResponseBody
	@ExceptionHandler(RuntimeException.class)
	public ModelAndView handleRuntimeException(HttpServletRequest req, HttpServletResponse resp, RuntimeException ex){
		//return "@ResponseBody error";
		return new ModelAndView("error");
	}
	
	// SimpleMappingExceptionResolver统一处理
	//@ExceptionHandler({NoHandlerFoundException.class, NoSuchRequestHandlingMethodException.class})
	//@ResponseStatus(value=HttpStatus.NOT_FOUND)
	public ResponseEntity<String> handle404(){
		return new ResponseEntity<String>("404", HttpStatus.OK);
	}
	
}
